package org.codehaus.activemq.message.util;

import java.io.ByteArrayOutputStream;

public class WireByteArrayOutputStream extends ByteArrayOutputStream
{
  public WireByteArrayOutputStream()
  {
    super(32);
  }

  public WireByteArrayOutputStream(int size)
  {
    super(size);
  }

  public void restart(int size)
  {
    this.buf = new byte[size];
    this.count = 0;
  }

  public void restart()
  {
    restart(32);
  }

  public void write(int b)
  {
    int newcount = this.count + 1;
    if (newcount > this.buf.length) {
      byte[] newbuf = new byte[Math.max(this.buf.length << 1, newcount)];
      System.arraycopy(this.buf, 0, newbuf, 0, this.count);
      this.buf = newbuf;
    }
    this.buf[this.count] = (byte)b;
    this.count = newcount;
  }

  public void write(byte[] b, int off, int len)
  {
    if ((off < 0) || (off > b.length) || (len < 0) || (off + len > b.length) || (off + len < 0)) {
      throw new IndexOutOfBoundsException();
    }
    if (len == 0) {
      return;
    }
    int newcount = this.count + len;
    if (newcount > this.buf.length) {
      byte[] newbuf = new byte[Math.max(this.buf.length << 1, newcount)];
      System.arraycopy(this.buf, 0, newbuf, 0, this.count);
      this.buf = newbuf;
    }
    System.arraycopy(b, off, this.buf, this.count, len);
    this.count = newcount;
  }

  public byte[] getData()
  {
    return this.buf;
  }

  public void reset()
  {
    this.count = 0;
  }
}